package com.imc.core.config.druid;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

/**
 * Created by tanweiping on 2018/7/24.
 */
/*
* 类描述：数据库连接池配置
* 开发者：tanweiping
* 创建日期：2018/8/7 10:00
*/
@ConditionalOnExpression("${druid.use:true}")
@Slf4j
@Configuration
public class DruidConfig {

    @Autowired
    DruidProperty druidProperty;

    /*
    * tanweiping  2018/8/7 10:17
    * 方法描述：DruidConfig的serlet注册及黑白名单
    */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        log.info("init Druid Monitor Servlet ...");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),
                "/druid/*");

        Optional.ofNullable(
                druidProperty.getAllowStr()
        ).ifPresent(
                s->// IP白名单
                        servletRegistrationBean.addInitParameter("allow", s)
        );

        Optional.ofNullable(
                druidProperty.getDencyStr()
        ).ifPresent(
                s->// IP黑名单(共同存在时，deny优先于allow)
                        servletRegistrationBean.addInitParameter("deny", s)
        );

        // 控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", druidProperty.getLogin().getUsername());
        servletRegistrationBean.addInitParameter("loginPassword", druidProperty.getLogin().getPassword());
        // 是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    /*
    * tanweiping  2018/8/7 10:18
    * 方法描述：DruidConfig的fliter处理
    */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
